package com.ygswglxt.notification.consumer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ygswglxt.common.Result;
import com.ygswglxt.notification.service.NotificationService;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
@ConditionalOnProperty(name = "rocketmq.name-server")
@RocketMQMessageListener(
    topic = "leave-topic",
    consumerGroup = "notification-consumer-group"
)
public class LeaveNotificationConsumer implements RocketMQListener<String> {
    
    @Autowired
    private NotificationService notificationService;
    
    private RestTemplate restTemplate = new RestTemplate();
    private static final String USER_SERVICE_URL = "http://localhost:8082/user/managers";
    
    // 查询所有经理ID（用于发送审批通知）
    private List<Long> getManagerIds() {
        try {
            Result result = restTemplate.getForObject(USER_SERVICE_URL, Result.class);
            if (result != null && result.getCode() != null && result.getCode().equals(200)) {
                List<Map<String, Object>> managers = (List<Map<String, Object>>) result.getData();
                List<Long> managerIds = new ArrayList<>();
                for (Map<String, Object> manager : managers) {
                    Long id = ((Number) manager.get("id")).longValue();
                    managerIds.add(id);
                }
                return managerIds;
            }
        } catch (Exception e) {
            System.err.println("查询经理列表失败: " + e.getMessage());
        }
        return new ArrayList<>();
    }
    
    @Override
    public void onMessage(String message) {
        System.out.println("========== 收到请假通知消息 ==========");
        System.out.println("消息内容: " + message);
        try {
            JSONObject jsonObject = JSON.parseObject(message);
            String type = jsonObject.getString("type");
            Long userId = jsonObject.getLong("userId");
            
            System.out.println("消息类型: " + type + ", 用户ID: " + userId);
            
            if ("LEAVE_APPLY".equals(type)) {
                // 请假申请通知（给所有经理）
                Long leaveId = jsonObject.getLong("leaveId");
                String leaveType = jsonObject.getString("leaveType");
                Integer days = jsonObject.getInteger("days");
                
                String typeName = "";
                if ("ANNUAL".equals(leaveType)) {
                    typeName = "年假";
                } else if ("SICK".equals(leaveType)) {
                    typeName = "病假";
                } else if ("PERSONAL".equals(leaveType)) {
                    typeName = "事假";
                } else if ("ADJUSTMENT".equals(leaveType)) {
                    typeName = "调休";
                }
                
                System.out.println("请假申请 - 类型: " + typeName + ", 天数: " + days + ", 记录ID: " + leaveId);
                
                // 查询所有经理，给每个经理发送通知
                List<Long> managerIds = getManagerIds();
                if (managerIds.isEmpty()) {
                    System.err.println("⚠️ 未找到经理，无法发送审批通知");
                } else {
                    for (Long managerId : managerIds) {
                        notificationService.createNotification(
                            managerId,
                            "APPROVAL_PENDING",
                            "待审批：请假申请",
                            "您有新的" + typeName + "申请需要审批，天数：" + days + "天",
                            leaveId,
                            "LEAVE"
                        );
                    }
                    System.out.println("✓ 已向 " + managerIds.size() + " 位经理发送请假审批通知");
                }
            } else if ("LEAVE_APPROVE".equals(type)) {
                // 审批结果通知（给申请人本人）
                Long leaveId = jsonObject.getLong("leaveId");
                String status = jsonObject.getString("status");
                String leaveType = jsonObject.getString("leaveType");
                Integer days = jsonObject.getInteger("days");
                
                String typeName = "";
                if ("ANNUAL".equals(leaveType)) {
                    typeName = "年假";
                } else if ("SICK".equals(leaveType)) {
                    typeName = "病假";
                } else if ("PERSONAL".equals(leaveType)) {
                    typeName = "事假";
                } else if ("ADJUSTMENT".equals(leaveType)) {
                    typeName = "调休";
                }
                
                String statusName = "APPROVED".equals(status) ? "已通过" : "已拒绝";
                System.out.println("请假审批结果 - 记录ID: " + leaveId + ", 状态: " + status);
                notificationService.createNotification(
                    userId, // 发给申请人本人
                    "APPROVAL_RESULT",
                    "审批结果：" + typeName + "申请",
                    "您的" + typeName + "申请（" + days + "天）" + statusName,
                    leaveId,
                    "LEAVE"
                );
                System.out.println("✓ 已向申请人 " + userId + " 发送审批结果通知");
            } else {
                System.out.println("⚠ 未知的消息类型: " + type);
            }
            System.out.println("========== 消息处理完成 ==========");
        } catch (Exception e) {
            System.err.println("❌ 处理消息失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

